//
//  HNThreeGoodEvaVC.m
//  优学荟管理系统
//
//  Created by edz on 2017/12/19.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HNThreeGoodEvaVC.h"
#import "HNThreeGoodNewEvaCell.h"
#import "HNThreeGoodEvaNewModel.h"
#import "HNThreeGoodEvaDetailVC.h"
#import "HMRedFlowerDetailsVC.h"

@interface HNThreeGoodEvaVC ()<UICollectionViewDelegate, UICollectionViewDataSource>
{
    __weak IBOutlet UICollectionView *_CollectionView;
    __weak IBOutlet UICollectionViewFlowLayout *_CollectionViewFlowLayout;
    __weak IBOutlet UILabel *_SelectNum; // 选中人数
    __weak IBOutlet UIButton *_AllSelect; // 全选按钮
    __weak IBOutlet UIView *headerView;
}
@property (nonatomic, strong) NSMutableArray <HNThreeGoodEvaNewModel *>*DataArr;
@property (nonatomic, assign) NSInteger AllNormalNum; // 所有未评价且为正常状态的数量 ，要网络获取成功后计算


@end

@implementation HNThreeGoodEvaVC

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(255, 255, 255)] forBarMetrics:(UIBarMetricsDefault)];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(51,51,51)}];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:ColorRGB(255,255,255)}];
    [self.navigationController.navigationBar setBackgroundImage:[LLTools createImageWithColor:ColorRGB(47, 204, 138)] forBarMetrics:(UIBarMetricsDefault)];

}


- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.title = @"三好评价";
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTargat:self action:@selector(Pop) image:@"icon_back_student_sign" highImage:@"icon_back_student_sign"];
    
    [_CollectionView registerNib:[UINib nibWithNibName:[HNThreeGoodNewEvaCell description] bundle:nil] forCellWithReuseIdentifier:@"Cell"];
    _CollectionViewFlowLayout.minimumLineSpacing = 8;
    _CollectionViewFlowLayout.minimumInteritemSpacing = 8;
    _CollectionViewFlowLayout.sectionInset = UIEdgeInsetsMake(8, 8, 8, 8);
    _CollectionViewFlowLayout.itemSize = CGSizeMake((kScreenWidth - 32) / 3, (kScreenWidth - 32) / 3 * 1.2);
    
    [self RefreshData];
}


#pragma mark - 网络
/**
 本页数据请求
 */
- (void)RefreshData
{
    [HUD showHUD];

    NSString *url;
    if (self.HNThreeGoodEvaMode == HNThreeGoodEvaModeCourseList) {
        // 课程列表
        url = [NSString stringWithFormat:@"yxhUser.do?action=getCourseRecordNewComment&teacherId=%@&lessonId=%@&pageNumber=1",self.teacherId,[self.ID stringValue]];
    } else if (self.HNThreeGoodEvaMode == HNThreeGoodEvaModeTeacher) {
        // 老师
        url = [NSString stringWithFormat:@"yxhUser.do?action=getCourseCommentStudent&teacherId=%@&lessonId=%@&pageNumber=1",self.teacherId,[self.ID stringValue]];
    } else {
        // 小当家
        url = [NSString stringWithFormat:@"yxhUser.do?action=getStepCount&teacherId=%@&lessonId=%@&pageNumber=1",self.teacherId,[self.ID stringValue]];
    }
    
    NSLog(@"%@ - %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    [NetManager Get:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        
        [HUD hideHUD];
        if ([Obj[@"code"] isEqualToNumber:@1000])
        {
            // 取模型
            NSArray *Arr = Obj[@"t"][@"dataList"];
            if (_DataArr.count != 0) {
                [_DataArr removeAllObjects];
            }
            // 转对象
            [Arr enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                HNThreeGoodEvaNewModel *Model = [[HNThreeGoodEvaNewModel alloc] init_ValuForKeyWithDict:obj];
                // 计算所有的正常数量
                self.AllNormalNum = [Model.type isEqualToNumber:@0] && ![Model.commentCount isEqualToNumber:Model.courseCount] ? self.AllNormalNum + 1:self.AllNormalNum;
                [self.DataArr addObject:Model];
            }];
            

            [_CollectionView reloadData];
        }
        else
        {
            [HUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [HUD hideHUD];
        [HUD showError:NetErr];
    }];
}

#pragma mark - CollectionView代理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
 
    return self.DataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    HNThreeGoodEvaNewModel *Model = self.DataArr[indexPath.item];
    HNThreeGoodNewEvaCell *Cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
    Cell.Model = Model;
    Cell.ClickSelect = ^(HNThreeGoodEvaNewModel *Model) {
        [self Action_ClickSelect:Model];
    };
    Cell.ClickDelete = ^(NSNumber *EnrollInfoId, NSNumber *ID) {
        [self deleteStudentWithID:ID errID:EnrollInfoId];
    };
    return Cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.HNThreeGoodEvaMode != HNThreeGoodEvaModeLittleMan) {
        return;
    }
    // 必须是小当家才生效
    HNThreeGoodEvaNewModel *Model = self.DataArr[indexPath.item];
     [NSString stringWithFormat:@"%@",Model.ID] ;
    HMRedFlowerDetailsVC *vc = [[HMRedFlowerDetailsVC alloc]init];
    vc.enrollInfoId = [NSString stringWithFormat:@"%@",Model.ID];
    vc.uid = [NSString stringWithFormat:@"%@",Model.O_UID];
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 删除学生
- (void)deleteStudentWithID:(NSNumber *)ID errID:(NSNumber *)errID {
    //    NSString *url = [NSString stringWithFormat:@"trainLesson.do?action=delStudentNotValid&uid=%@&enrollInfoId=%@&type=1",ID,errID];
    
    
//    NSString *url = @"trainLesson.do?action=delStudentNotValid";
//    NSDictionary *params = @{
//                             @"uid":ID,
//                             @"enrollInfoId":errID,
//                             @"type": @"2"
//                             };
    
    NSString *url = [NSString stringWithFormat:@"trainLesson.do?action=delStudentNotValid&uid=%@&enrollInfoId=%@&type=2",ID,errID];
    //
    NSLog(@"%@ %@",LLBaseURL(url),[AccountTool shareAccountTool].currentAccount.authCode);
    
    
    [SVProgressHUD setDefaultStyle:(SVProgressHUDStyleCustom)];
    [SVProgressHUD  setBackgroundColor:ColorRGB(4, 4, 4)];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]];
    [SVProgressHUD showWithStatus:LLLoading];
    
    [NetManager Post:LLBaseURL(url) Auth:YES Params:nil Success:^(id Obj) {
        if ([[Obj valueForKey:@"code"]integerValue] == 1000) {
            [SVProgressHUD setStatus:Obj[@"msg"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
                [self RefreshData];
            });
        }
    } Fail:^(NSError *Error) {
        
        [SVProgressHUD dismiss];
    }];
}

#pragma mark - 事件
/** 点击选择 */
- (void)Action_ClickSelect:(HNThreeGoodEvaNewModel *)Model {
 
    // 查看是否要响应选中事件 isSign为1时才响应，2不允许操作
    // 并且将所有的未完成都进行禁用
//    if (![Model.commentCount isEqualToNumber:Model.courseCount]) {
//
//        // 更改状态
//        Model.Selected = !Model.Selected;
//        if (Model.Selected == YES) {
//        // 如果这个Model是正常状态，则将所有未完成都禁点
//            [self.DataArr enumerateObjectsUsingBlock:^(HNThreeGoodEvaNewModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//
//            // 当前选中正常状态 obj的为未完成与未评价状态
//                if ([Model.type isEqualToNumber:@0] && [obj.type isEqualToNumber:@1] && Model != obj  && ![obj.commentCount isEqualToNumber:obj.courseCount] ) {
//
//                    obj.Enable = NO;
//                }
//
//                // 当前选中为未完成状态，全部设置为不可点击
//                if (![Model.type isEqualToNumber:@0] && Model != obj  && ![obj.commentCount isEqualToNumber:obj.courseCount]) {
//
//                    obj.Enable = NO;
//                }
//            }];
//            _SelectNum.text = [@(([_SelectNum.text integerValue] + 1)) stringValue];
//        } else {
//            // 取消选中
//            __block BOOL IsFull = YES;
//            // 查下是不是最后一个被取消选中的
//            [self.DataArr enumerateObjectsUsingBlock:^(HNThreeGoodEvaNewModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                // 不是最后一个
//                if (obj.Selected == YES  && ![obj.commentCount isEqualToNumber:obj.courseCount]) {
//                    IsFull = NO;
//                    *stop = YES;
//                }
//            }];
//            // 没有一个被行踪了，恢复所有状态
//            if (IsFull) {
//                [self.DataArr enumerateObjectsUsingBlock:^(HNThreeGoodEvaNewModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//                    if (Model != obj  && ![obj.commentCount isEqualToNumber:obj.courseCount]) {
//
//                        obj.Enable = YES;
//                    }
//                }];
//            }
//            _SelectNum.text = [@(([_SelectNum.text integerValue] - 1)) stringValue];
//        }
//    }
//    _AllSelect.selected = self.AllNormalNum == [_SelectNum.text integerValue] ? YES:NO;
//    [_CollectionView reloadData];
    
    
    // ***************** 12-28khuann:取消多选及全选功能 *****************
    [self.DataArr enumerateObjectsUsingBlock:^(HNThreeGoodEvaNewModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.Selected = NO;
    }];
    Model.Selected = YES;
    _SelectNum.text = @"1";
    [_CollectionView reloadData];
}

/** 全选 */
- (IBAction)Action_AllSelect:(UIButton *)Button {
    
    Button.selected = !Button.selected;
    /** 所有未评价的都先设置初始值 */
    [self.DataArr enumerateObjectsUsingBlock:^(HNThreeGoodEvaNewModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        /** 防止思路断开，下列判断单独分开写 */
        // 只有未评价能响应
        if (![obj.commentCount isEqualToNumber:obj.courseCount]) {
            obj.Selected = NO;
            obj.Enable = YES;
        }
        // 同时未完成状态的禁点
        if (![obj.type isEqualToNumber:@0]  && ![obj.commentCount isEqualToNumber:obj.courseCount]) {
            obj.Enable = Button.selected ? NO:YES;
        }
        
        if ([obj.type isEqualToNumber:@0]  && ![obj.commentCount isEqualToNumber:obj.courseCount]) {
            
            obj.Selected = Button.selected;
        }
    }];
    _SelectNum.text = [@(Button.selected ? self.AllNormalNum:0) stringValue];
//    Button.selected = Button.selected && [_SelectNum.text isEqualToString:@"0"] ? NO:YES;
    [_CollectionView reloadData];
}

/** 评价 */
- (IBAction)Action_Sure:(UIButton *)sender {
    
    // 找出被选中的那些
    if ([_SelectNum.text integerValue] <= 0) {
        
        [SVProgressHUD showErrorWithStatus:@"请选择学生评价"];
        return;
    }
    
    NSMutableArray <NSString *>*EnrollArr = [NSMutableArray array];
    NSMutableArray <NSString *>*UIDArr = [NSMutableArray array];
    __block NSString *ImgStr = @"";
    __block NSString *Name = @"";
    __block NSString *LessonName = @"";
    __block NSNumber *TempId = @0;
    [self.DataArr enumerateObjectsUsingBlock:^(HNThreeGoodEvaNewModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![obj.commentCount isEqualToNumber:obj.courseCount] && obj.Selected == YES) {
            [EnrollArr addObject:[obj.ID stringValue]];
            [UIDArr addObject:[obj.O_UID stringValue]];
            if ([_SelectNum.text isEqualToString:@"1"]) {
                ImgStr = obj.avatar;
                Name = obj.O_petName;
                LessonName = self.Name;
                TempId = obj.tempId;
            }
        }
    }];
    HNThreeGoodEvaDetailVC *VC = [HNThreeGoodEvaDetailVC new];
    VC.ID = self.ID;
    VC.EnrollInfoIds = [EnrollArr componentsJoinedByString:@","];
    VC.Uids = [UIDArr componentsJoinedByString:@","];
    
    // 单个学生
    if ([_SelectNum.text isEqualToString:@"1"]) {
        VC.ImgStr = ImgStr;
        VC.Name = Name;
        VC.LessonName = LessonName;
        VC.TempID = TempId;
    }
    VC.PoP = ^{
        self.AllNormalNum = 0;
         _SelectNum.text = @"0";
        [self.DataArr removeAllObjects];
        [_CollectionView reloadData];
        [self RefreshData];
    };
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)Pop {
    
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - Get
- (NSMutableArray<HNThreeGoodEvaNewModel *> *)DataArr {
    
    if (!_DataArr) {
        
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}
@end
